﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using GuiaCiudad.Resources;
using MVVMComun;
using System.Threading;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.IO;

namespace GuiaCiudad
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor

       public List<Image> images= new List<Image>();
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += MainPage_Loaded;
            this.Unloaded += MainPage_Unloaded;
           
        }

        void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {

      

        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
                        
         //   LoadOffline();
        
        }

        private async Task LoadOffline()
        {

            var localfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            var folderToSave = await localfolder.CreateFolderAsync("Fotos", Windows.Storage.CreationCollisionOption.OpenIfExists);
            var file = await folderToSave.GetFileAsync("fotos.dat");

            DataContractSerializer ds = new DataContractSerializer(new List<Foto>().GetType());

            var stream = await file.OpenStreamForReadAsync();
           
            var fotos = ds.ReadObject(stream) as List<Foto>;

            foreach (Foto f in fotos)
            {

               // f.Url = folderToSave.Path + f.Titulo + ".jpg";

                file = await folderToSave.GetFileAsync(f.Titulo+".jpg");

                stream = await file.OpenStreamForReadAsync();
                System.Windows.Media.Imaging.BitmapImage Bi = new System.Windows.Media.Imaging.BitmapImage();
                Bi.SetSource(stream);

                ii.Source = Bi;

                break;
            }

         


        }

        private void StackPanel_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Microsoft.Phone.Tasks.WebBrowserTask wbt = new Microsoft.Phone.Tasks.WebBrowserTask();
            wbt.Uri = new Uri(((StackPanel)sender).Tag.ToString());
            wbt.Show();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Image_Loaded(object sender, RoutedEventArgs e)
        {
            Image i = sender as Image;
            images.Add(i);
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            var c = images.Count;
        }

        
    }
}